'''
    Example external client for BlueSky.

    When you run this file, make sure python knows where to find BlueSky:

    PYTHONPATH=/path/to/your/bluesky python textclient.py
'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QComboBox
from PySide2 import QtWidgets
from bluesky.network import Client
import random
from time import sleep
import datetime

# The echo textbox, command line, and bluesky network client as globals
echobox = None
cmdline = None
bsclient = None


class TextClient(Client):
    '''
        Subclassed Client with a timer to periodically check for incoming data,
        an overridden event function to handle data, and a stack function to
        send stack commands to BlueSky.
    '''
    def __init__(self):
        super().__init__()
        self.timer = QTimer()
        self.timer.timeout.connect(self.receive)
        self.timer.start(20)

    def event(self, name, data, sender_id):
        ''' Overridden event function to handle incoming ECHO commands. '''
        if name == b'ECHO' and echobox is not None:
            echobox.echo(**data)

    def stack(self, text):
        ''' Stack function to send stack commands to BlueSky. '''
        self.send_event(b'STACKCMD', text)


class Echobox(QTextEdit):
    ''' Text box to show echoed text coming from BlueSky. '''
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMaximumHeight(50)
        self.setReadOnly(True)
        self.setFocusPolicy(Qt.NoFocus)

    def echo(self, text, flags=None):
        ''' Add text to this echo box. '''
        self.append(text)
        self.verticalScrollBar().setValue(self.verticalScrollBar().maximum())


class Cmdline(QTextEdit):
    ''' Wrapper class for the command line. '''
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMaximumHeight(50)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    def keyPressEvent(self, event):
        ''' Handle Enter keypress to send a command to BlueSky. '''
        if event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return:
            if bsclient is not None:
                bsclient.stack(self.toPlainText())
                echobox.echo(self.toPlainText())
            self.setText('')
        else:
            super().keyPressEvent(event)

                                   
class ComboxDemo(QComboBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        # 单个添加条目（苏雨）
        self.addItem('aircraft_1')
        self.addItem('aircraft_2')
        self.addItem('aircraft_3')
        # 多个添加条目（苏雨）
        self.addItems(['aircraft_4', 'aircraft_5', 'aircraft_6'])

        ''' 信号（苏雨）
        self.cb.currentIndexChanged[str].connect(self.print_value) # 条目发生改变，发射信号，传递条目内容（苏雨）
        self.cb.currentIndexChanged[int].connect(self.print_value)  # 条目发生改变，发射信号，传递条目索引（苏雨）
        self.cb.highlighted[str].connect(self.print_value)  # 在下拉列表中，鼠标移动到某个条目时发出信号，传递条目内容（苏雨）
        self.cb.highlighted[int].connect(self.print_value)  # 在下拉列表中，鼠标移动到某个条目时发出信号，传递条目索引（苏雨）
    def print_value(self, i):
        print(i)
        '''


class WorkThread(QThread):
  # 初始化线程（苏雨）
  def __int__(self):
    super(WorkThread, self).__init__()
  #线程运行函数（苏雨）
  def run(self):
    while True:
      global T_value
      global P_value
      T_value = random.randint(200,225)
      P_value = random.randint(150,200)
      print(T_value, P_value)
      #经纬度变量，改括号里的值可以改变窗口动态数值（苏雨）
      edita1.setText(str(T_value))
      edita2.setText(str(P_value))       
      #刷新率（苏雨）
      sleep(0.1)


def Mytimer(self):
  timer = QTimer(self)
  timer.timeout.connect(self.update)
  timer.start(100)


def update(self):
  self.edita1.setText(str(T_value))
  self.edita2.setText(str(P_value))
  global SUM_value
  SUM_value = T_value + P_value
  self.edita5.setText(str(SUM_value))
 


if __name__ == '__main__':
    # Construct the Qt main object
    app = QApplication([])
    edita1 = QLineEdit() 
    edita2 = QLineEdit()
    
    workThread = WorkThread()
    workThread.start() 
    # Create a window with a stack text box and a command line (suyu)
    win = QWidget()
    win.resize(400,300)
    win.setWindowTitle('suyu')
    layout = QFormLayout()
    win.setLayout(layout)
    echobox = Echobox(win)
    cmdline = Cmdline(win)
    label1 = QLabel(win)
    label2 = QLabel(win)
    label3 = QLabel(win)
    label4 = QLabel(win)
    label5 = QLabel(win)        
    bg_gender = QButtonGroup(win)
    bg_No = QButtonGroup(win)  
    cbox = ComboxDemo(win) 



   
#Add a text description to the window (suyu)    
    label1.setText("BlueSky command line output:")
    label1.setAutoFillBackground(True) 
    palette = QPalette()        
    palette.setColor(QPalette.Window,Qt.yellow)  
    label1.setPalette(palette) 
    label1.setAlignment( Qt.AlignLeft)
     
    label2.setText("BlueSky command line intput:")
    label2.setAutoFillBackground(True) 
    palette = QPalette()        
    palette.setColor(QPalette.Window,Qt.yellow)  
    label2.setPalette(palette) 
    label2.setAlignment( Qt.AlignLeft)
    
    label3.setText("BlueSky aircraft selsection:")
    label3.setAutoFillBackground(True) 
    palette = QPalette()        
    palette.setColor(QPalette.Window,Qt.yellow)  
    label3.setPalette(palette) 
    label3.setAlignment( Qt.AlignLeft)
        
    label4.setText("Longitude of selected aircraft:")
    label4.setAutoFillBackground(True) 
    palette = QPalette()        
    palette.setColor(QPalette.Window,Qt.green)  
    label4.setPalette(palette) 
    label4.setAlignment( Qt.AlignLeft)
        
    label5.setText("Latitude of selected aircraft:")
    label5.setAutoFillBackground(True) 
    palette = QPalette()        
    palette.setColor(QPalette.Window,Qt.green)  
    label5.setPalette(palette) 
    label5.setAlignment( Qt.AlignLeft)
    
  
    
#Insert control into window (suyu)
    layout.addWidget(label1)
    layout.addWidget(echobox)
    layout.addWidget(label2) 
    layout.addWidget(cmdline)    
    layout.addWidget( QPushButton('FlightGear'))
    layout.addWidget( QPushButton('BlueSky'))
    '''
    layout.addWidget( QPushButton(str(3)))
    layout.addWidget( QPushButton(str(4)))
    layout.addWidget( QPushButton(str(5)))  
    '''  
    layout.addWidget(label3)
    layout.addWidget(cbox)
    layout.addWidget(label4)    
    layout.addRow(edita1)
    layout.addWidget(label5)
    layout.addRow(edita2) 


    win.show()

    # Create and start BlueSky client
    bsclient = TextClient()
    bsclient.connect(event_port=11000, stream_port=11001)

    # Start the Qt main loop
    app.exec_()
